'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Plus, Search, Filter, Edit, Trash2, Eye, BookOpen } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'


interface Question {
  id: string
  content: string
  options: string[]
  correctAnswer: number
  explanation: string
  difficulty: number
  topicId: string
  topicName?: string
  createdAt: string
}

export default function QuestionsManagePage() {
  const [questions, setQuestions] = useState<Question[]>([])
  const [filteredQuestions, setFilteredQuestions] = useState<Question[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedDifficulty, setSelectedDifficulty] = useState<number | null>(null)
  const [selectedTopic, setSelectedTopic] = useState<string>('')
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  // 模拟题库数据
  const mockQuestions: Question[] = [
    {
      id: 'q1',
      content: '小明有5个苹果，小红有3个苹果，他们一共有多少个苹果？',
      options: ['6个', '7个', '8个', '9个'],
      correctAnswer: 2,
      explanation: '5 + 3 = 8，所以他们一共有8个苹果。',
      difficulty: 1,
      topicId: 'basic-addition',
      topicName: '基础加法',
      createdAt: new Date().toISOString()
    },
    {
      id: 'q2',
      content: '一个长方形的长是8厘米，宽是5厘米，它的周长是多少厘米？',
      options: ['26厘米', '24厘米', '28厘米', '30厘米'],
      correctAnswer: 0,
      explanation: '长方形周长 = 2×(长+宽) = 2×(8+5) = 2×13 = 26厘米',
      difficulty: 2,
      topicId: 'rectangle-perimeter',
      topicName: '长方形周长',
      createdAt: new Date().toISOString()
    },
    {
      id: 'q3',
      content: '鸡兔同笼，共有头20个，脚54只，问鸡有多少只？',
      options: ['13只', '14只', '15只', '16只'],
      correctAnswer: 0,
      explanation: '设鸡有x只，兔有(20-x)只。2x + 4(20-x) = 54，解得x = 13',
      difficulty: 4,
      topicId: 'chicken-rabbit-cage',
      topicName: '鸡兔同笼',
      createdAt: new Date().toISOString()
    }
  ]

  useEffect(() => {
    loadQuestions()
  }, [])

  useEffect(() => {
    filterQuestions()
  }, [questions, searchQuery, selectedDifficulty, selectedTopic])

  const loadQuestions = async () => {
    try {
      setIsLoading(true)

      // 使用模拟数据（实际应该从API获取）
      setQuestions(mockQuestions)
    } catch (err) {
      console.error('加载题库错误:', err)
      setError('加载题库时发生错误')
    } finally {
      setIsLoading(false)
    }
  }

  const filterQuestions = () => {
    let filtered = questions

    // 搜索过滤
    if (searchQuery) {
      filtered = filtered.filter(q => 
        q.content.toLowerCase().includes(searchQuery.toLowerCase()) ||
        q.topicName?.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }

    // 难度过滤
    if (selectedDifficulty !== null) {
      filtered = filtered.filter(q => q.difficulty === selectedDifficulty)
    }

    // 知识点过滤
    if (selectedTopic) {
      filtered = filtered.filter(q => q.topicId === selectedTopic)
    }

    setFilteredQuestions(filtered)
  }

  const getDifficultyLabel = (difficulty: number) => {
    const labels = { 1: '入门', 2: '基础', 3: '进阶', 4: '高级', 5: '竞赛' }
    return labels[difficulty as keyof typeof labels] || '未知'
  }

  const getDifficultyColor = (difficulty: number) => {
    const colors = {
      1: 'bg-green-100 text-green-800',
      2: 'bg-blue-100 text-blue-800', 
      3: 'bg-yellow-100 text-yellow-800',
      4: 'bg-orange-100 text-orange-800',
      5: 'bg-red-100 text-red-800'
    }
    return colors[difficulty as keyof typeof colors] || 'bg-gray-100 text-gray-800'
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载题库中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8"
        >
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            题库管理
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            管理奥数题库，支持增删改查和分类筛选
          </p>
        </motion.div>

        {/* 操作栏 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="mb-6"
        >
          <Card glassmorphism className="backdrop-blur-xl">
            <CardContent className="p-6">
              <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
                <div className="flex flex-col sm:flex-row gap-4 flex-1">
                  {/* 搜索框 */}
                  <div className="relative flex-1 max-w-md">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Input
                      placeholder="搜索题目内容或知识点..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="pl-10"
                      glassmorphism
                    />
                  </div>

                  {/* 难度筛选 */}
                  <select
                    value={selectedDifficulty || ''}
                    onChange={(e) => setSelectedDifficulty(e.target.value ? Number(e.target.value) : null)}
                    className="px-4 py-2 rounded-lg bg-white/20 backdrop-blur-sm border border-white/30 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">全部难度</option>
                    <option value="1">入门</option>
                    <option value="2">基础</option>
                    <option value="3">进阶</option>
                    <option value="4">高级</option>
                    <option value="5">竞赛</option>
                  </select>
                </div>

                {/* 添加题目按钮 */}
                <Button
                  variant="glassmorphism"
                  className="glassmorphism-button"
                  onClick={() => {
                    // TODO: 打开添加题目对话框
                    alert('添加题目功能开发中...')
                  }}
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加题目
                </Button>
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {/* 错误提示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 rounded-lg bg-red-100 border border-red-300 text-red-700"
          >
            {error}
          </motion.div>
        )}

        {/* 题目列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="grid gap-6"
        >
          {filteredQuestions.length === 0 ? (
            <Card glassmorphism className="backdrop-blur-xl">
              <CardContent className="p-12 text-center">
                <BookOpen className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                <h3 className="text-xl font-semibold text-gray-600 mb-2">暂无题目</h3>
                <p className="text-gray-500">
                  {searchQuery || selectedDifficulty || selectedTopic 
                    ? '没有找到符合条件的题目' 
                    : '题库为空，请添加题目'
                  }
                </p>
              </CardContent>
            </Card>
          ) : (
            filteredQuestions.map((question, index) => (
              <motion.div
                key={question.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1 * index }}
              >
                <Card glassmorphism className="backdrop-blur-xl hover:shadow-lg transition-all duration-300">
                  <CardHeader>
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${getDifficultyColor(question.difficulty)}`}>
                            {getDifficultyLabel(question.difficulty)}
                          </span>
                          <span className="px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                            {question.topicName}
                          </span>
                        </div>
                        <CardTitle className="text-lg text-gray-800 dark:text-gray-200">
                          {question.content}
                        </CardTitle>
                      </div>
                      <div className="flex gap-2 ml-4">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            // TODO: 预览题目
                            alert('预览功能开发中...')
                          }}
                        >
                          <Eye className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            // TODO: 编辑题目
                            alert('编辑功能开发中...')
                          }}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            // TODO: 删除题目
                            if (confirm('确定要删除这道题目吗？')) {
                              alert('删除功能开发中...')
                            }
                          }}
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <div>
                        <h4 className="font-medium text-gray-700 dark:text-gray-300 mb-2">选项：</h4>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                          {question.options.map((option, idx) => (
                            <div
                              key={idx}
                              className={`p-2 rounded-lg text-sm ${
                                idx === question.correctAnswer
                                  ? 'bg-green-100 text-green-800 border border-green-300'
                                  : 'bg-gray-100 text-gray-700'
                              }`}
                            >
                              {String.fromCharCode(65 + idx)}. {option}
                              {idx === question.correctAnswer && (
                                <span className="ml-2 text-xs font-medium">✓ 正确答案</span>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                      
                      {question.explanation && (
                        <div>
                          <h4 className="font-medium text-gray-700 dark:text-gray-300 mb-2">解析：</h4>
                          <p className="text-sm text-gray-600 dark:text-gray-400 bg-blue-50 p-3 rounded-lg">
                            {question.explanation}
                          </p>
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            ))
          )}
        </motion.div>

        {/* 统计信息 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="mt-8"
        >
          <Card glassmorphism className="backdrop-blur-xl">
            <CardContent className="p-6">
              <div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-300">
                <span>
                  显示 {filteredQuestions.length} / {questions.length} 道题目
                </span>
                <span>
                  最后更新：{new Date().toLocaleDateString()}
                </span>
              </div>
            </CardContent>
          </Card>
        </motion.div>
      </div>
    </div>
  )
}
